<template>
	<view style="display: flex;
	flex-direction: column;height: 100%;">	
		<view style="flex: 1;">
			<view class="Have">已经配对的设备</view>
			<view class="equipment" style="margin-top: 5px;" v-for="(item,index) in pairedBlueDevice" :key="index">
				<!-- left: ;
				right: ; -->
				<view class="equi_left">
					<img src="@/static/image/blue1.png" alt="">
				</view>
				<view class="equi_right" @tap="print(item.address)">
					<view class="equi_title">{{item.name}}</view>
					<view class="equi_title">{{item.address}}</view>
				</view>
			</view>
		</view>
		<view style="flex: 2;margin-top: 40px;">
			<view class="Have">其他可用设备</view>
			<view class="equipment" style="margin-top: 5px;"  v-for="(item,index) in pairBlueDevice" :key="index">
				<!-- left: ;
				right: ; -->
				<view class="equi_left">
					<img src="@/static/image/blue1.png" alt="">
				</view>
				<view class="equi_right" @tap="tipToBu()">
					<view class="equi_title">{{item.name}}</view>
					<view class="equi_title">{{item.address}}</view>
				</view>
			</view>
		</view>
		<view class="search" >
			<button @tap="searchDevices">搜索设备</button>
		</view>
	</view>
</template>
<script>
	// import service from '../../../service.js';
	const PrinterJobs = require('../../printer/printerjobs.js')
	const printerUtil = require('../../printer/printerutil.js')
	// import {
	//     mapState,
	//     mapMutations
	// } from 'vuex'
	// import mInput from '../../components/m-input.vue'

	export default {
		
		data() {
			return {
				providerList: [],
				hasProvider: false,
				account: '',
				password: '',
				positionTop: 0,
				buttonText: "搜索设备",
				pairBlueDevice: [],
				pairedBlueDevice: []
			}
		},
		// computed: mapState(['forcedLogin']),
		methods: {
			// ...mapMutations(['login']),
			// initProvider() {
			//     const filters = ['weixin', 'qq', 'sinaweibo'];
			//     uni.getProvider({
			//         service: 'oauth',
			//         success: (res) => {
			//             if (res.provider && res.provider.length) {
			//                 for (let i = 0; i < res.provider.length; i++) {
			//                     if (~filters.indexOf(res.provider[i])) {
			//                         this.providerList.push({
			//                             value: res.provider[i],
			//                             image: '../../static/img/' + res.provider[i] + '.png'
			//                         });
			//                     }
			//                 }
			//                 this.hasProvider = true;
			//             }
			//         },
			//         fail: (err) => {
			//             console.error('获取服务供应商失败：' + JSON.stringify(err));
			//         }
			//     });
			// },
			// initPosition() {
			//     /**
			//      * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
			//      * 反向使用 top 进行定位，可以避免此问题。
			//      */
			//     this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
			// },
			// ArrayBuffer转16进度字符串示例
			// ab2hex(buffer) {
			// 	const hexArr = Array.prototype.map.call(
			// 		new Uint8Array(buffer),
			// 		function(bit) {
			// 			return ('00' + bit.toString(16)).slice(-2)
			// 		}
			// 	)
			// 	return hexArr.join(',')
			// },
			tipToBu(){
				Api.showTip("此设备为配对，请先配对");
				
			},
			print(mac_address) {
				console.log("mac_address:" + mac_address);
				if (!mac_address) {
					// mui.toast('请选择蓝牙打印机');
					return;
				}
				uni.showModal({
					title: '提示',
					content: "是否选择此设备",
					style: "z-index:9999",
					success: function(res) {
						if (res.confirm) {
							uni.setStorageSync("bluetoothName",mac_address);
							uni.navigateBack({
								delta:1
							})
						} else if (res.cancel) {
							// sureClick(false);
						}
					}
				});
				// var device = null,
				// 	BAdapter = null,
				// 	BluetoothAdapter = null,
				// 	uuid = null,
				// 	main = null,
				// 	that = this,
				// 	bluetoothSocket = null;
				// main = plus.android.runtimeMainActivity();
				// BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				// var UUID = plus.android.importClass("java.util.UUID");
				// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
				// BAdapter = BluetoothAdapter.getDefaultAdapter();
				// device = BAdapter.getRemoteDevice(mac_address);
				// plus.android.importClass(device);
				// bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
				// plus.android.importClass(bluetoothSocket);
				// if (!bluetoothSocket.isConnected()) {
				// 	console.log('检测到设备未连接，尝试连接....');
				// 	bluetoothSocket.connect();
				// }
				// console.log('设备已连接');
				// if (bluetoothSocket.isConnected()) {
				// 	console.log('设备已连接1');
				// 	var outputStream = bluetoothSocket.getOutputStream();
				// 	plus.android.importClass(outputStream);
				// 	//var buffer = "打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试\r\n";  
				// 	var printerJobs = new PrinterJobs();
				// 	var esc = "打印测试\r\n";
				// 	printerJobs
				// 		.print('2018年12月5日17:34')
				// 		.print(printerUtil.fillLine())
				// 		.setAlign('ct')
				// 		.setSize(2, 2)
				// 		.print('#20晓涛饿了么外卖')
				// 		.setSize(1, 1)
				// 		.print('切尔西Chelsea')
				// 		.setSize(2, 2)
				// 		.print('在线支付(已支付)')
				// 		.setSize(1, 1)
				// 		.print('订单号：5415221202244734')
				// 		.print('下单时间：2017-07-07 18:08:08')
				// 		.setAlign('lt')
				// 		.print(printerUtil.fillAround('一号口袋'))
				// 		.print(printerUtil.inline('晓涛 * 1', '15'))
				// 		.print(printerUtil.fillAround('其他'))
				// 		.print('餐盒费：1')
				// 		.print('[赠送周树明冰红茶] * 1')
				// 		.print(printerUtil.fillLine())
				// 		.setAlign('rt')
				// 		.print('原价：￥16')
				// 		.print('总价：￥16')
				// 		.setAlign('lt')
				// 		.print(printerUtil.fillLine())
				// 		.print('备注')
				// 		.print("无")
				// 		.print(printerUtil.fillLine())
				// 		.println();
				// 	let buffer = printerJobs.buffer();
				// 	var buffer1 = plus.android.invoke(esc, 'getBytes', 'gbk');
				// 	const maxChunk = 256;
				// 	const delay = 20;
				// 	var length = 0;
				// 	for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
				// 		let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
				// 		let array = Array.prototype.slice.call(new Int8Array(subPackage));
				// 		outputStream.write(array)
				// 	}
				// 	//outputStream.write(buffer);  
				// 	outputStream.flush();
				// 	device = null; //这里关键  
				// 	bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误  
				// }
			},

			buf2hex(buffer) { // buffer is an ArrayBuffer
				return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
			},
			searchDevices() {
				console.log("进来了");
				var address = 'a';
				var main = plus.android.runtimeMainActivity();
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				console.log("开始搜索设备");
				var filter = new IntentFilter();
				var bdevice = new BluetoothDevice();
				var on = null;
				var un = null;
				var that = this;
				// var vlist1 = document.getElementById('list1'); //注册容器用来显示未配对设备  
				// vlist1.innerHTML = ''; //清空容器  
				// var vlist2 = document.getElementById('list2'); //注册容器用来显示未配对设备  
				// vlist2.innerHTML = ''; //清空容器  
				// var button1 = document.getElementById('bt1');  
				// button1.disabled=true;  
				// button1.value='正在搜索请稍候';  
				uni.showLoading({
					title:"搜索中...",
					mask:true
				})
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var len = lists.size();
				console.log(len);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					console.log(d.getName());
					var Temp = {
						"name": "",
						"address": ""
					};
					Temp["name"] = d.getName();
					Temp["address"] = d.getAddress();
					that.pairedBlueDevice.push(Temp);
				}
				that.buttonText = "正在搜索请稍候";
				BAdapter.startDiscovery(); //开启搜索  
				var receiver;
				receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
					onReceive: function(context, intent) { //实现onReceiver回调函数  
						plus.android.importClass(intent); //通过intent实例引入intent类，方便以后的‘.’操作  
						console.log(intent.getAction()); //获取action  
						if (intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
							main.unregisterReceiver(receiver); //取消监听  
							//button1.disabled=false;  
							//button1.value='搜索设备';  
							that.buttonText = "搜索设备";
							uni.hideLoading();
							// console.log("搜索结束")
						} else {
							var BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
							//判断是否配对  
							if (BleDevice.getBondState() == bdevice.BOND_NONE) {
								//console.log("未配对蓝牙设备：" + BleDevice.getName() + '    ' + BleDevice.getAddress());  
								//参数如果跟取得的mac地址一样就配对  
								if (address == BleDevice.getAddress()) {
									if (BleDevice.createBond()) { //配对命令.createBond()  
										// console.log("配对成功");
										var Temp = {
											"name": "",
											"address": ""
										};
										Temp["name"] = BleDevice.getName();
										Temp["address"] = BleDevice.getAddress();
										that.pairBlueDevice.push(Temp);
										//pairBlueDevice
										// var li2 = document.createElement('li'); //注册  
										// li2.setAttribute('id', BleDevice.getAddress()); //打印机mac地址  
										// li2.setAttribute('onclick', 'print(id)'); //注册click点击列表进行打印  
										// li2.innerText = BleDevice.getName();  
										// vlist2.appendChild(li2);  
									}

								} else {
									if (BleDevice.getName() != on) { //判断防止重复添加  
										// var li1 = document.createElement('li'); //注册  
										// li1.setAttribute('id', BleDevice.getAddress()); //打印机mac地址  
										// li1.setAttribute('onclick', 'searchDevices(id)'); //注册click点击列表进行配对  
										// on = BleDevice.getName(); 
										console.log("未配对蓝牙设备：" + BleDevice.getName() + '    ' + BleDevice.getAddress());
										var Temp = {
											"name": "",
											"address": ""
										};
										Temp["name"] = BleDevice.getName();
										Temp["address"] = BleDevice.getAddress();
										that.pairBlueDevice.push(Temp);
										// li1.innerText = on;  
										//vlist1.appendChild(li1);  

									}

								}
							} else {
								console.log("已配对蓝牙设备：" + BleDevice.getName() + '    ' + BleDevice.getAddress());
								if (BleDevice.getName() != un) { //判断防止重复添加  
									console.log("已配对蓝牙设备：" + BleDevice.getName() + '    ' + BleDevice.getAddress());
									on = BleDevice.getName();
									var Temp = {
										"name": "",
										"address": ""
									};
									Temp["name"] = BleDevice.getName();
									Temp["address"] = BleDevice.getAddress();
									that.pairedBlueDevice.push(Temp);
								}
							}
						}

					}
				});

				filter.addAction(bdevice.ACTION_FOUND);
				filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
				filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
				filter.addAction(BAdapter.ACTION_STATE_CHANGED);

				main.registerReceiver(receiver, filter); //注册监听  
			},

			bluetooth_list() {
				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				var Context = plus.android.importClass("android.content.Context");
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var len = lists.size();
				var that = this;
				console.log(len);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					console.log(d.getName());
					var Temp = {
						"name": "",
						"address": ""
					};
					Temp["name"] = d.getName();
					Temp["address"] = d.getAddress();
					that.pairedBlueDevice.push(Temp);
				}
			},
			bindLogin() {
				/**
				 * 客户端对账号信息进行一些必要的校验。
				 * 实际开发中，根据业务需要进行处理，这里仅做示例。
				 */
				if (this.account.length < 5) {
					uni.showToast({
						icon: 'none',
						title: '账号最短为 5 个字符'
					});
					return;
				}
				if (this.password.length < 6) {
					uni.showToast({
						icon: 'none',
						title: '密码最短为 6 个字符'
					});
					return;
				}
				/**
				 * 下面简单模拟下服务端的处理
				 * 检测用户账号密码是否在已注册的用户列表中
				 * 实际开发中，使用 uni.request 将账号信息发送至服务端，客户端在回调函数中获取结果信息。
				 */
				const data = {
					account: this.account,
					password: this.password
				};
				const validUser = service.getUsers().some(function(user) {
					return data.account === user.account && data.password === user.password;
				});
				if (validUser) {
					this.toMain(this.account);
				} else {
					uni.showToast({
						icon: 'none',
						title: '用户账号或密码不正确',
					});
				}
			},
			oauth(value) {
				uni.login({
					provider: value,
					success: (res) => {
						uni.getUserInfo({
							provider: value,
							success: (infoRes) => {
								/**
								 * 实际开发中，获取用户信息后，需要将信息上报至服务端。
								 * 服务端可以用 userInfo.openId 作为用户的唯一标识新增或绑定用户信息。
								 */
								this.toMain(infoRes.userInfo.nickName);
							}
						});
					},
					fail: (err) => {
						console.error('授权登录失败：' + JSON.stringify(err));
					}
				});
			},

			toMain(userName) {
				this.login(userName);
				/**
				 * 强制登录时使用reLaunch方式跳转过来
				 * 返回首页也使用reLaunch方式
				 */
				if (this.forcedLogin) {
					uni.reLaunch({
						url: '../main/main',
					});
				} else {
					uni.navigateBack();
				}

			}
		},

		onReady() {
			//this.requestPermission();
		}
	}
</script>

<style>
.Have{
	height: 70upx;
	width: 100%;
	background-color: #007AFF;
	color: #fff;
	text-align: center;
	
	line-height: 70upx;
	font-size: 14px;
	/* display: flex;
	justify-content: center;
	align-content: center; */
	}
	.equipment{
		height: 90upx;
		background-color: #00B7B8;
		display: flex;
	}
	.equi_left{
		flex: 1;
		background-color: #07C160;
		display: flex;
		justify-content: center;
		align-items: center;
		
	}
	.equi_title{
		padding-left: 15px;
	}
	.equi_left>img{
		width: 30px;
		height: 30px;
		
	}
	.equi_right{
		flex: 4;
		background-color: #ccc;
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		/* align-items: center; */
	}
	.search{
		height: 80upx;
		width: 100%;
		position: fixed;
		bottom: 5px;
		left: 0;
		background: #FFF;
	}
	.search button{
		width: 95%;
		margin: auto;
		height: 74upx;
		margin-top: 3upx;
		background-color: #0081FF;
		text-align: center;
		border-radius: 5px;
		color: #fff;
		font-size: 16px;
		line-height: 75upx;
		/* background: #fff; */
		box-shadow: 0 7px 14px 0 rgba(59, 65, 94, 0.1), 0 3px 6px 0 rgba(0, 0, 0, 0.07);
	}
	
</style>
